(function () {
  "use strict";
  // dpr > scale = 1/dpr
  const docEL = document.documentElement;
  // 设备宽限定
  const maxWidth = 540;
  const minWidth = 320;

  // h获取viewport标签
  const viewportEL = document.querySelector('meta[name="viewport"]');
  // 获取设备像素比
  let dpr = window.devicePixelRatio || 1;
  // 处理DPR
  dpr = dpr >= 3 ? 3 : dpr >= 2 ? 2 : 1;

  docEL.setAttribute("data-dpr", dpr);
  docEL.setAttribute("max-width", maxWidth);
  docEL.setAttribute("min-width", minWidth);

  const scale = 1 / dpr;

  const content = `width=device-width, initial-scale= ${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`;

  if (viewportEL) {
    viewportEL.setAttribute("content", content);
  } else {
    viewportEL = document.createElement("meta");
    viewportEL.setAttribute("name", "viewport");
    viewportEL.setAttribute("content", content);
    document.head.appendChild(viewportEL);
  }
  setRemUnit();
  window.addEventListener("resize", setRemUnit);
  function setRemUnit() {
    var ratio = 18.75;
    var viewWidth = docEL.getBoundingClientRect().width || window.innerHeight;
    if (maxWidth && viewWidth / dpr > maxWidth) {
      viewWidth = maxWidth * dpr;
    } else if (minWidth && viewWidth / dpr < minWidth) {
      viewWidth = minWidth * dpr;
    }
    docEL.style.fontSize = viewWidth / ratio + "px";
  }
})();
